// pages/pay/pay.js
const app = getApp()
import { request } from "../../request/index.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bids:[],
    books:[],
    count: 0,
    phone: '',
    address:'',
    name: '',
    outTradeNo: '',
    time: 0,
    countdown:'',
    show: false,
    endTime: 0,
  },
  // 取消订单
  jmp_cancel(){
    console.log("dianjiquxiao...")
    const that = this
    wx.showModal({
      title: '是否取消订单？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (result.confirm) {
          request({
            url: '/order/cancel',
            method: "GET",
            data: {
              // 下面以分为单位的
              "outTradeNo": that.data.outTradeNo,
            }
          })
            .then(result => {
              console.log(result)
              const errTips = result.data.message
              setTimeout(()=>{
                wx.redirectTo({
                  url: '../../pages/cart_real/cart_real'
                })
              },1000)
          })
        }
      },
      fail: () => {},
      complete: () => {}
    });
      
  },
  // 付款申请
  jmp_pay() {
    console.log("dianji...")
    const that = this
    if (wx.getStorageSync('userPhone') && wx.getStorageSync('add')) {
      console.log("jinlaile")
      // 调接口下单
      request({
        url: '/order/payMoney',
        method: "GET",
        data: {
          // 下面以分为单位的
          "outTradeNo": that.data.outTradeNo,
        }
      })
        .then(result => {
          console.log(result)
          const errTips = result.data.message
          // 接口下单失败
          if (result.data.code != 20000) {
            wx.showToast({
              title: errTips,
              icon: 'error',
              duration: 2000
            })
            setTimeout(()=>{
              wx.redirectTo({
                url: '../../pages/index/index'
              })
            },2000)
            
          }
          // 接口下单成功 调微信付款
          else{

            wx.requestPayment({
              timeStamp: result.data.data.timeStamp,
              nonceStr: result.data.data.nonceStr,
              package: result.data.data.package,
              signType: 'RSA',
              paySign: result.data.data.paySign,
              // 付款成功
              success(res) {
                console.log(res)
                  wx.requestSubscribeMessage({
                    tmplIds: ['Hpjd0alVWAqSfwMX9mMFqh5AMubFrFLyEvPKmzefA6s'],
                    success(res) {
                      console.log(res)
                    }
                  })
                  request({ 
                    url: '/order/paySuccess',
                    method: "GET",
                    data:
                      {
                        "outTradeNo": result.data.data.outTradeNo,
                      }
                   })
                   .then(result1=>{
                     console.log(result1)
                     wx.redirectTo({
                      url: '../../pages/buy/buy'
                    })
                   })
                  console.log(' paySuccess ')
              },
              // 付款失败
              fail(err) {
                console.log(err)
                request({ 
                  url: '/order/payFail',
                  method: "GET",
                  data:{
                    outTradeNo: result.data.data.outTradeNo,
                  }
                })
                .then(result=>{
                  console.log(result)
                  console.log(' payCancel ')
                })
              }
            })
          }
        })
        .catch(error=>{
          console.log("error")
          console.log(error)
        })
    }
    else {
      wx.showToast({
        title: '个人信息仍需完善噢',
        icon: 'none',
        duration: 1000
      })
    }
  },

  // 倒计时
  countdown(){
    var nowTime = new Date().getTime() 
    this.setData({
      endTime: Math.floor(this.data.time/1000+1800-nowTime/1000)
    })
    var minute=Math.floor(this.data.endTime  / 60 );
    var second=this.data.endTime  % 60
    if(second<10){
        second='0'+second;
        this.setData({
            countdown:minute+':'+second
        })
    }else{
        this.setData({
            countdown:minute+':'+second
        })
    }
    this.setData({
      endTime:this.data.endTime-1
    })
    setTimeout(this.countdown, 1000);
}, 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options.bids)
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    request({
      url: '/water',
      method: "GET",
    })
    .then(result=>{
      console.log(result)
      this.setData({
        books: result.data.data.list,
        count: result.data.data.total,
        outTradeNo: result.data.data.outTradeNo
      })
      console.log(that.data.books)
      console.log(that.data.count)
      console.log(that.data.outTradeNo)
      if(that.data.outTradeNo){
        that.setData({
          time: result.data.data.createTime,
          show: !that.data.show
        })
        that.countdown()
      }
    })
    var sphone = wx.getStorageSync('userPhone')
    var saddress = wx.getStorageSync('add')
    var suserinfo = wx.getStorageSync('userinfo')
    that.setData({
      phone: sphone,
      address: saddress,
      name: suserinfo.nickName
    })
    console.log(123)
    console.log(that.data.name)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})